var url = require('../config').url;
var toast = require('toast');
var HttpPost = require('request').httpPost;
var trackEvent = require('track_event').trackEvent;

function Pay (orderSysNo) {
		var self = this;

		HttpPost({
			url: url.Pay_UnifiedGoPay + '?OrderSysNo=' + orderSysNo,
			success: function (res) {
				if (res.code == 0) {
					var data = res.value;
					wx.requestPayment({
						timeStamp: data.timestamp,
						nonceStr: data.noncestr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						success: function () {
							//支付成功，手动调用绑券接口，绑定成功后将soInfo设置到storage，跳转到支付成功页
							//延迟3秒，等待支付状态同步成功后再请求绑券
							var second = 3;
							function cd() {
								wx.showLoading({
									title: '正在处理支付结果' + second + '...',
									mask: true
								});
								second--;
								if (second < 0) {
									PaySuccess(orderSysNo);
								} else {
									setTimeout(cd, 1000);
								}
							}

							cd();
						},
						fail: function (res) {
							wx.setStorageSync('payFailedTitle', '支付未完成，请重新支付');
							wx.switchTab({
								url: '/page/myorderlist/myorderlist' 
							});
						}
					});
				} else {
					toast(res.msg, 'fail', 1500);
          setTimeout(function () {
            wx.setStorageSync('payFailedTitle', '支付未完成，请重新支付');
            wx.switchTab({
              url: '/page/myorderlist/myorderlist'
            });
          }, 2000);
				}
			},
			fail: function (res) {
				toast(res.errMsg);
			}
		})
	}

function PaySuccess(orderSysNo) {
		var self = this;

		HttpPost({
			url: url.Pay_MiniOrderPaySuccess,
			data: { orderSysNo: orderSysNo },
			success: function (res) {
				if (res.code == 0 && res.value.couponRemark && res.value.couponList && res.value.couponList.length) {
					wx.setStorageSync('soInfo', { couponRemark: res.value.couponRemark, couponList: res.value.couponList });

          // 埋点-订单支付成功
          try {
            trackEvent([{
              kind: 'event', type: 'purchase', name: 'createOrderSucceeded', userInfo: {
                soid: orderSysNo,
                activitySysNo: wx.getStorageSync('activitySysNo')
              }
            }])
          } catch (e) { }
				}
			},
			complete: function () {
				wx.hideLoading();
				wx.reLaunch({
					url: '/page/order/ordersuccess'
				});
			},
		})
	}
module.exports = {
  pay: Pay,
  paySuccess: PaySuccess
};